//
//  UIView+BlockGesture.m
//  company
//
//  Created by  任辰东 on 2019/1/2.
//  Copyright © 2019 Ryan. All rights reserved.
//

#import "UIView+BlockGesture.h"
#import <objc/runtime.h>
static char MYTActionHandlerTapBlockKey;
static char MYTActionHandlerTapGestureKey;
static char MYTActionHandlerLongPressBlockKey;
static char MYTActionHandlerLongPressGestureKey;

@implementation UIView (BlockGesture)
- (void)setTapActionWithBlock:(GestureActionBlock)block
{
    UITapGestureRecognizer *gesture = objc_getAssociatedObject(self, &MYTActionHandlerTapGestureKey);
    if (!gesture) {
        gesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleActionForTapGesture:)];
        [self addGestureRecognizer:gesture];
        objc_setAssociatedObject(self, &MYTActionHandlerTapGestureKey, gesture, OBJC_ASSOCIATION_RETAIN);
    }
    objc_setAssociatedObject(self, &MYTActionHandlerTapBlockKey, block, OBJC_ASSOCIATION_COPY);
    
}

- (void)handleActionForTapGesture:(UITapGestureRecognizer *)gesture
{
    if (gesture.state == UIGestureRecognizerStateRecognized)
    {
        GestureActionBlock block = objc_getAssociatedObject(self, &MYTActionHandlerTapBlockKey);
        if (block) {
            block();
        }
    }
}

- (void)setLongPressActionWithBlock:(longPressGestureActionBlock)block{
    UILongPressGestureRecognizer *gesture = objc_getAssociatedObject(self, &MYTActionHandlerLongPressGestureKey);
    if (!gesture)
    {
        gesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleActionForLongPressGesture:)];
        gesture.minimumPressDuration = 1;
        [self addGestureRecognizer:gesture];
        objc_setAssociatedObject(self, &MYTActionHandlerLongPressGestureKey, gesture, OBJC_ASSOCIATION_RETAIN);
    }
    objc_setAssociatedObject(self, &MYTActionHandlerLongPressBlockKey, block, OBJC_ASSOCIATION_COPY);
}

- (void)handleActionForLongPressGesture:(UITapGestureRecognizer *)gesture
{
    if (gesture.state == UIGestureRecognizerStateBegan)
    {
        longPressGestureActionBlock block = objc_getAssociatedObject(self, &MYTActionHandlerLongPressBlockKey);
        if (block){
            block();
        }
    }
}
@end
